<template>
  <div class="pad-20 bgc-default" v-loading="loading">
    <!-- 订单信息 -->
    <div>
      <span class="font-20">订单信息</span>
      <div class="mar-t-10 bg-color-white pad-20">
        <el-row>
          <el-col :span="12">
            <table class="base-info">
              <tr>
                <td class="left">平台订单号：</td>
                <td class="right">
                  <el-input v-model="orderObj.externalOrderNo" class="width-250"></el-input>
                </td>
              </tr>
              <tr>
                <td class="left">平台类型：</td>
                <td class="right">
                  <el-select class="width-250" v-model="orderObj.externalPlatformType" @change="doChangePlatformType">
                    <el-option label="无" value=""></el-option>
                    <template v-for="(val, key) in dict.platformType">
                      <el-option :key="key" :label="val" :value="key"></el-option>
                    </template>
                  </el-select>
                </td>
              </tr>
              <tr>
                <td class="left">平台店铺：</td>
                <td class="right">
                  <el-select class="width-250" v-model="orderObj.externalShopId" :disabled="!orderObj.externalPlatformType">
                    <el-option label="无" value=""></el-option>
                    <el-option v-for="(item, index) in shopList" :key="index" :label="item.shopName" :value="item.shopId"></el-option>
                  </el-select>
                </td>
              </tr>
              <tr>
                <td class="left">卖家备注：</td>
                <td class="right">
                  <el-input type="textarea" :rows="3" class="width-250" v-model="orderObj.sellerWords"></el-input>
                </td>
              </tr>
            </table>
          </el-col>
          <el-col :span="12">
            <table class="base-info">
              <tr>
                <td class="left">收货人：</td>
                <td class="right">
                  <el-input v-model="orderObj.customerNickname" class="width-300"></el-input>
                </td>
              </tr>
              <tr>
                <td class="left">收货人电话：</td>
                <td class="right">
                  <el-input v-model="orderObj.customerPhone" class="width-300"></el-input>
                </td>
              </tr>
              <tr>
                <td class="left">收货地址：</td>
                <td class="right">
                  <el-select class="mar-r-3 width-140" v-model="orderObj.customerProvinceCode" placeholder="请选择省份" @change="doChangeCity(orderObj.customerProvinceCode)">
                    <el-option v-for="item in provinceList" :key="item.areaCode" :label="item.areaName" :value="item.areaCode">
                    </el-option>
                  </el-select>
                  <el-select class="mar-r-3 width-140" v-model="orderObj.customerCityCode" placeholder="请选择城市" @change="doChangeDistrict(orderObj.customerCityCode)">
                    <el-option v-for="item in cityList" :key="item.areaCode" :label="item.areaName" :value="item.areaCode">
                    </el-option>
                  </el-select>
                  <el-select v-model="orderObj.customerDistrictCode" placeholder="请选择区县" class="width-140">
                    <el-option v-for="item in districtList" :key="item.areaCode" :label="item.areaName" :value="item.areaCode">
                    </el-option>
                  </el-select>
                  <div class="mar-t-5">
                    <el-input v-model="orderObj.customerAddress" style="width: 435px"></el-input>
                  </div>
                </td>
              </tr>
            </table>
          </el-col>
        </el-row>
      </div>
    </div>

    <!-- 平台商品明细 -->
    <div class="mar-t-20">
      <span class="font-20">商品信息</span>
      <div class="mar-t-10 bg-color-white pad-20">
        <div class="mar-b-20">
          <label>运费：</label>
          <el-input v-model="orderObj.freight"
            class="width-300"
            @keyup.native="orderObj.freight = checkInputNum(orderObj.freight)">
            <template slot="append">元</template>
          </el-input>
        </div>
        <div class="mar-b-20">
          <div class="mar-b-10"><label>订单商品：</label></div>
          <el-button type="text" size="medium" @click="doAddGoods()">添加商品</el-button>
          <el-table :data="orderObj.orderGoodsList">
            <el-table-column min-width="250px" label="商品信息">
              <template slot-scope="scope">
                <div class="flex v-align-c">
                  <label><img :src="scope.row.goodsImageUrl" class="t-goods-pic"></label>
                  <div class="pad-l-10">
                    <div class="line-2">{{ scope.row.goodsTitle }}</div>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column width="180px" label="规格" prop="skuDetail" align="left">
            </el-table-column>
            <el-table-column width="130px" label="数量" prop="goodsNum" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.goodsNum"
                  class="width-80"
                  @keyup.native="scope.row.goodsNum = checkInputPositiveNum(scope.row.goodsNum)">
                </el-input>
              </template>
            </el-table-column>
            <el-table-column width="130px" label="单价" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.goodsPrice"
                  class="width-100"
                  @keyup.native="scope.row.goodsPrice = checkInputNum(scope.row.goodsPrice)">
                </el-input>
              </template>
            </el-table-column>

            <el-table-column v-if="distributorRoleFlag" width="130px" label="分销价" prop="goodsDistributePrice" align="left">
            </el-table-column>

            <el-table-column width="130px" label="金额" align="center">
              <template slot-scope="scope">
                <span>{{ (scope.row.goodsNum * scope.row.goodsPrice).toFixed(2) }}</span>
              </template>
            </el-table-column>

            <el-table-column v-if="distributorRoleFlag" width="130px" label="分销金额" align="center">
              <template slot-scope="scope">
                <span>{{ (scope.row.goodsNum * scope.row.goodsDistributePrice).toFixed(2) }}</span>
              </template>
            </el-table-column>

            <el-table-column width="100px" label="操作" align="center">
              <template slot-scope="scope">
                <el-button type="text" size="medium" @click="doRemove(scope)">移除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>

    <!-- 底部按钮区 -->
    <div class="pad-20" align="center">
      <el-button @click="doBack">返回上一级</el-button>
      <el-button type="primary" @click="doSave">保存</el-button>
    </div>

    <!-- 选择商品dialog -->
    <el-dialog width="1000px" v-el-drag-dialog title="选择商品" :visible.sync="selectSkuVisible">
      <select-goods-sku :showFlag="selectSkuVisible"
       :crossBorderType="1"
       @callback="doCallbackSelect">
      </select-goods-sku>
    </el-dialog>

  </div>
</template>

<script>
  import { getHandOrder, saveHandOrder } from '@/api/order/handOrder'
  import { listProvince, listCity, listDistrict } from '@/api/area/area'
  import { listThirdShop } from '@/api/user/third-shop'
  import { getDictByGroupName } from '@/api/common/common'
  import elDragDialog from '@/directive/el-dragDialog'
  import selectGoodsSku from '@/views/goods/order/components/select-goods-sku'

  export default {
    directives: {
      elDragDialog
    },
    components: {
      selectGoodsSku
    },
    data() {
      return {
        // 第三方订单对象
        orderObj: {
          handOrderId: '',
          orderNo: '',
          enterpriseId: '',
          externalPlatformType: '',
          externalOrderNo: '',
          externalShopId: '',
          customerNickname: '',
          customerPhone: '',
          customerProvinceCode: '',
          customerCityCode: '',
          customerDistrictCode: '',
          customerAddress: '',
          freight: '0',
          orderGoodsList: []
        },
        // 数据字典
        dict: {
          platformType: {}
        },
        // 省集合
        provinceList: [],
        // 市集合
        cityList: [],
        // 区集合
        districtList: [],
        // 店铺集合
        shopList: [],
        // 分销商角色flag
        distributorRoleFlag: false,
        loading: false,
        selectSkuVisible: false
      }
    },
    // 初始化页面
    created() {
      this.distributorRoleFlag = this.getSystemRoleType() === '4'
      // 获取省信息
      listProvince().then(response => {
        this.provinceList = response.data
      })
      // 获取数据字典
      getDictByGroupName('ThirdOrderDTO').then(response => {
        Object.assign(this.dict, response.data)
      })
      const handOrderId = this.getCurrentPage().query.handOrderId
      if (handOrderId) {
        this.orderObj.handOrderId = handOrderId
        this.init()
      }
    },
    methods: {
      // 初始化
      init() {
        this.loading = true
        getHandOrder(this.orderObj.handOrderId).then(response => {
          if (response.isError) {
            this.loading = false
            return
          }
          Object.assign(this.orderObj, response.data)
          const params = {
            enterpriseId: this.getEnterpriseId(),
            memberId: this.getMemberId(),
            platformType: this.orderObj.externalPlatformType
          }
          listThirdShop(params).then(response => {
            this.loading = false
            this.shopList = response.data
            this.orderObj.externalPlatformType = this.orderObj.externalPlatformType.toString()
            this.doChangeCity(this.orderObj.customerProvinceCode, this.orderObj.customerCityCode, this.orderObj.customerDistrictCode)
          })
        })
      },
      // 平台类型切换事件
      doChangePlatformType() {
        const params = {
          enterpriseId: this.getEnterpriseId(),
          memberId: this.getMemberId(),
          platformType: this.orderObj.externalPlatformType
        }
        listThirdShop(params).then(response => {
          if (response.isError) return
          this.shopList = response.data
          this.orderObj.externalShopId = ''
        })
      },
      // 市修改事件
      doChangeCity(provinceCode, cityCode, townCode) {
        this.cityList = []
        this.districtList = []
        this.orderObj.customerCityCode = ''
        this.orderObj.customerDistrictCode = ''
        if (provinceCode) {
          listCity(provinceCode).then(response => {
            this.cityList = response.data
          })
          this.orderObj.customerCityCode = cityCode
          this.doChangeDistrict(cityCode, townCode)
        }
      },
      // 区修改事件
      doChangeDistrict(cityCode, townCode) {
        this.districtList = []
        this.orderObj.customerDistrictCode = ''
        if (cityCode) {
          listDistrict(cityCode).then(response => {
            this.districtList = response.data
          })
          this.orderObj.customerDistrictCode = townCode
        }
      },
      // 添加商品事件
      doAddGoods() {
        this.selectSkuVisible = true
      },
      // 商品选择回调事件
      doCallbackSelect(res) {
        if (res.skuId) {
          const exist = this.orderObj.orderGoodsList.filter(item => item.skuId === res.skuId)
          if (exist.length > 0) {
            this.$message({ message: '商品已添加', type: 'error' })
            return
          }
        } else {
          const exist = this.orderObj.orderGoodsList.filter(item => item.goodsId === res.goodsId)
          if (exist.length > 0) {
            this.$message({ message: '商品已添加', type: 'error' })
            return
          }
        }
        const goods = {
          goodsId: res.goodsId,
          goodsNum: 1,
          goodsPrice: res.sellPrice,
          goodsDistributePrice: res.distributePrice ? res.distributePrice : 0,
          goodsTitle: res.title,
          goodsImageUrl: res.imageUrl,
          skuId: res.skuId,
          skuDetail: res.skuDetail
        }
        if (!this.distributorRoleFlag) {
          goods.goodsDistributePrice == null
        }
        this.orderObj.orderGoodsList.push(goods)
        this.selectSkuVisible = false
      },
      // 移除事件
      doRemove(scope) {
        this.orderObj.orderGoodsList.splice(scope.$index, 1)
      },
      // 确定事件
      doSave() {
        if (!this.orderObj.customerNickname) {
          this.$message({ message: '收货人不能为空', type: 'error' })
          return
        }
        if (!this.orderObj.customerPhone) {
          this.$message({ message: '收货人电话不能为空', type: 'error' })
          return
        }
        if (!this.orderObj.customerProvinceCode) {
          this.$message({ message: '省不能为空', type: 'error' })
          return
        }
        if (!this.orderObj.customerCityCode) {
          this.$message({ message: '市不能为空', type: 'error' })
          return
        }
        if (!this.orderObj.customerDistrictCode) {
          this.$message({ message: '区不能为空', type: 'error' })
          return
        }
        if (!this.orderObj.customerAddress) {
          this.$message({ message: '详细地址不能为空', type: 'error' })
          return
        }
        const validGoodsList = this.orderObj.orderGoodsList
        if (validGoodsList.length === 0) {
          this.$message({ message: '请选择商品', type: 'error' })
          return
        }
        const goodsNumList = validGoodsList.filter(item => !item.goodsNum)
        if (goodsNumList.length > 0) {
          this.$message({ message: '存在数量为0的商品，请设置数量', type: 'error' })
          return
        }
        if (this.distributorRoleFlag) {
          const invalidZeroPriceList = validGoodsList.filter(item => item.goodsDistributePrice === 0)
          if (invalidZeroPriceList.length > 0) {
            this.$message({ message: '分销价不能为0', type: 'error' })
            return
          }
          const invalidPriceList = validGoodsList.filter(item => parseFloat(item.goodsDistributePrice) > parseFloat(item.goodsPrice))
          if (invalidPriceList.length > 0) {
            this.$message({ message: '商品单价不能小于分销价', type: 'error' })
            return
          }
        }
        this.loading = true
        this.orderObj.enterpriseId = this.getEnterpriseId()
        this.orderObj.memberId = this.getMemberId()
        saveHandOrder(this.orderObj).then(response => {
          this.loading = false
          if (response.isError) return
          this.$message({ message: '保存成功', type: 'success' })
          this.$router.push({ path: '/order/change-order' })
        })
      },
      // 返回事件
      doBack() {
        this.$router.go(-1)
      }
    }
  }
</script>

<style lang="less" scoped>
  .base-info {
    width: 100%;
    line-height: 45px;
    .left {
      display: flex;
      justify-content: flex-end;
    }
  }
</style>
